package com.studentsys.listener;

import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;

@WebListener
public class OnlineListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
    //服务器启动成功,就会有一个全局域对象,用他来存储网站在线人数
    private ServletContext context = null;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        context = servletContextEvent.getServletContext();
        //将在线人数默认初始化为0
        context.setAttribute("count",0);

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
    //用户登录成功,会向对象中存用户信息,会修改网站在线人数+1
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        //取出全局域中的count值
        int count = (int) context.getAttribute("count");
        count++;
        context.setAttribute("count",count);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }


    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    //当用户安全退出后,网站的在线人数-1
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        int count = (int) context.getAttribute("count");
        count--;
        context.setAttribute("count",count);
    }
}
